package com.example.administrator.waitloadinganim;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class LoadingDialog extends Dialog {

    private Window mWindow;

    private boolean mShowProgress = true;

    private ImageView mLoadingLogo;

    public LoadingDialog(Context context) {
        super(context);
        init(context);

    }

    public LoadingDialog(Context context, int theme) {
        super(context, theme);
        init(context);
    }

    private void init(Context context) {
        if (context instanceof Activity) {
            setOwnerActivity((Activity) context);
        }

        this.mWindow = getWindow();
        mWindow.requestFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.widget_loading);
        mLoadingLogo = (ImageView) findViewById(R.id.loadinglogo);
    }

    public static LoadingDialog show(Context context, CharSequence message) {
        return show(context, message, false);
    }

    public static LoadingDialog show(Context context, CharSequence message, boolean cancelable) {
        return show(context, message, cancelable, null);
    }

    public static LoadingDialog show(Context context, CharSequence message, boolean cancelable,
                                     OnCancelListener cancelListener) {
        LoadingDialog dialog = new LoadingDialog(context, R.style.ProgressLoadingTheme);
        dialog.setCancelable(cancelable);
        dialog.setOnCancelListener(cancelListener);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        return dialog;
    }

    @Override
    public void show() {
        Activity activity = getOwnerActivity();
        if (activity == null || activity.isFinishing()) {
            return;
        }

       

        if (mShowProgress) {

            if (mLoadingLogo.getAnimation() == null) {
                rotateLoading(2000, mLoadingLogo, 0, 359, null);
            }

        }

        super.show();
    }
    private void rotateLoading(int duration, View view, int startDegree, int endDegree, Animation.AnimationListener listener) {
        Animation animationR = new RotateAnimation(startDegree, endDegree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animationR.setDuration(duration);
        if (listener != null)
            animationR.setAnimationListener(listener);
        animationR.setFillAfter(true);
        animationR.setRepeatCount(Animation.INFINITE);
        LinearInterpolator lin = new LinearInterpolator();
        animationR.setInterpolator(lin);
        view.startAnimation(animationR);
    }
    @Override
    public void dismiss() {

        mLoadingLogo.clearAnimation();

        super.dismiss();
    }
}
